package com.beta.inventory;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


/**
 * {@link Inventory} with observers {@link PullListener}.
 */
public class SimpleInventory implements Inventory {
	
	// to prevent accidental unsynchronized access to the map
	private Map<String, Integer> items = Collections.synchronizedMap(new HashMap<String, Integer>());

	// dependency
	private PullListener pullListener;
	
	public void pull(String itemName) {
		
		updateItemQuantity(itemName, -1);
		
		pullListener.replenish(itemName);
	}

	private void updateItemQuantity(String itemName, int quantity) {
		if (itemsByName(itemName) > 0 ) {
			addItem(itemName, itemsByName(itemName) + quantity);
		}
	}

	public void setPullObserver(PullListener pullObserver) {
		this.pullListener = pullObserver;
	}

	public Integer itemsByName(String itemName) {
		return (items.get(itemName) != null)? items.get(itemName) : 0;
	}

	public void addItem(String itemName, int quantity) {
		items.put(itemName, quantity);
	}

}
